package com.tj.jinzao.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewStub;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.tandong.bottomview.view.BottomView;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tj.jinzao.App;
import com.tj.jinzao.ChatManager;
import com.tj.jinzao.R;
import com.tj.jinzao.adapter.HeadUserAdapter;
import com.tj.jinzao.adapter.MessageAdapter;
import com.tj.jinzao.adapter.SmallVideoViewAdapter;
import com.tj.jinzao.adapter.StartLiveAdapter;
import com.tj.jinzao.adapter.UserInfoAdapter;
import com.tj.jinzao.api.ApiRetrofit;
import com.tj.jinzao.api.ApiService;
import com.tj.jinzao.api.SubscriberCallBack;
import com.tj.jinzao.base.BaseVideoActivity;
import com.tj.jinzao.base.ConstantApp;
import com.tj.jinzao.callback.AGEventHandler;
import com.tj.jinzao.callback.ILiveView;
import com.tj.jinzao.callback.VideoViewEventListener;
import com.tj.jinzao.common.Constant;
import com.tj.jinzao.manager.UserManager;
import com.tj.jinzao.model.FollowFan;
import com.tj.jinzao.model.FriendBean;
import com.tj.jinzao.model.GiftBean;
import com.tj.jinzao.model.LiveUserBean;
import com.tj.jinzao.model.MessageBean;
import com.tj.jinzao.model.MessageListBean;
import com.tj.jinzao.model.MessageLiveComment;
import com.tj.jinzao.model.ReportBean;
import com.tj.jinzao.model.ResultResponse;
import com.tj.jinzao.model.User;
import com.tj.jinzao.model.VideoStatusData;
import com.tj.jinzao.utils.MessageUtil;
import com.tj.jinzao.utils.ToastUtils;
import com.tj.jinzao.utils.Util;
import com.tj.jinzao.widgets.ChooseLiveUserDialog;
import com.tj.jinzao.widgets.FaceBeautificationPopupWindow;
import com.tj.jinzao.widgets.GridVideoViewContainer;
import com.tj.jinzao.widgets.HorizontialListView;
import com.tj.jinzao.widgets.KeyMapDailog;
import com.tj.jinzao.widgets.RoundedImageView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.agora.rtc.Constants;
import io.agora.rtc.IRtcEngineEventHandler;
import io.agora.rtc.RtcEngine;
import io.agora.rtc.video.VideoCanvas;
import io.agora.rtc.video.VideoEncoderConfiguration;
import io.agora.rtm.ErrorInfo;
import io.agora.rtm.ResultCallback;
import io.agora.rtm.RtmChannel;
import io.agora.rtm.RtmChannelListener;
import io.agora.rtm.RtmChannelMember;
import io.agora.rtm.RtmClient;
import io.agora.rtm.RtmClientListener;
import io.agora.rtm.RtmMessage;
import io.agora.rtm.RtmStatusCode;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * Created by LiuYX on 2019/4/22.
 * 直播
 */

public class StartLiveActivity extends BaseVideoActivity implements ILiveView<List<FriendBean>>, View.OnClickListener, AGEventHandler {
    private HorizontialListView horizon_head_lv;
    private HeadUserAdapter headUserAdapter;
    private LinearLayout beauty_lay, chat_lay, gift_lay, comment_lay,content_bottom;
    private ImageView back_comment, up_image, gift, back_image, beauty, chat;
    private TextView comment_content, attent;
    private GridVideoViewContainer mGridVideoViewContainer;
    public int mViewType = VIEW_TYPE_DEFAULT;
    private RelativeLayout content_lay;
    private TextView send;

    public static final int VIEW_TYPE_DEFAULT = 0;

    public static final int VIEW_TYPE_SMALL = 1;

    private RelativeLayout mSmallVideoViewDock;

    private final HashMap<Integer, SurfaceView> mUidsList = new HashMap<>(); // uid = 0 || uid == EngineConfig.mUid
    private SmallVideoViewAdapter mSmallVideoViewAdapter;
    private RecyclerView mRecyclerView;
    protected ApiService mApiService = ApiRetrofit.getInstance().getApiService();

    private CompositeSubscription mCompositeSubscription;


    public void detachView() {
        onUnsubscribe();
    }

    //RXjava取消注册，以避免内存泄露
    public void onUnsubscribe() {
        if (mCompositeSubscription != null && mCompositeSubscription.hasSubscriptions()) {
            mCompositeSubscription.unsubscribe();
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String permissions[], @NonNull int[] grantResults) {
//        log.debug("onRequestPermissionsResult " + requestCode + " " + Arrays.toString(permissions) + " " + Arrays.toString(grantResults));
        switch (requestCode) {
            case ConstantApp.PERMISSION_REQ_ID_RECORD_AUDIO: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    checkSelfPermission(Manifest.permission.CAMERA, ConstantApp.PERMISSION_REQ_ID_CAMERA);
                } else {
                    finish();
                }
                break;
            }
            case ConstantApp.PERMISSION_REQ_ID_CAMERA: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, ConstantApp.PERMISSION_REQ_ID_WRITE_EXTERNAL_STORAGE);
                    ((App) getApplication()).initWorkerThread();
                    workThreadInited();
                } else {
                    finish();
                }
                break;
            }
            case ConstantApp.PERMISSION_REQ_ID_WRITE_EXTERNAL_STORAGE: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                } else {
                    finish();
                }
                break;
            }
        }
    }

    protected void workThreadInited() {
        isLode = true;
        initUIandEvent();

    }

    private boolean isBroadcaster(int cRole) {
        return cRole == Constants.CLIENT_ROLE_BROADCASTER;
    }

    private boolean isBroadcaster() {
        return isBroadcaster(config().mClientRole);
    }

    /*
     * API CALL: leave and release channel
     */
    private void leaveAndReleaseChannel() {
        if (mRtmChannel != null) {
            mRtmChannel.leave(null);
            mRtmChannel.release();
            mRtmChannel = null;
        }
    }

    @Override
    protected void onDestroy() {
        deInitUIandEvent();
        super.onDestroy();
        if (mIsPeerToPeerMode) {
            MessageUtil.addMessageListBeanList(new MessageListBean(roomName, mMessageBeanList));
        } else {
            leaveAndReleaseChannel();
        }
        exitLive();
        if(mRtmClient!=null){
            mRtmClient.logout(null);
        }
        mChatManager.unregisterListener(mClientListener);
        detachView();
    }

    protected void deInitUIandEvent() {
        doLeaveChannel();
        event().removeEventHandler(this);
        mUidsList.clear();
    }

    private void doLeaveChannel() {
        worker().leaveChannel(config().mChannel);
        if (isBroadcaster()) {
            worker().preview(false, null, 0);
        }
    }

    //是否加载完成
    private boolean isLode = false;
    User user;
    private ChatManager mChatManager;
    private RtmClient mRtmClient;
    private RtmClientListener mClientListener;
    private RtmChannel mRtmChannel;
    private int mChannelMemberCount = 1;

    /**
     * API CALL: send message to a channel
     */
    private void sendChannelMessage(String content) {
        // step 1: create a message
        RtmMessage message = mRtmClient.createMessage();
        message.setText(content);

        // step 2: send message to channel
        mRtmChannel.sendMessage(message, new ResultCallback<Void>() {

            @Override
            public void onSuccess(Void aVoid) {
            }

            @Override
            public void onFailure(ErrorInfo errorInfo) {
                // refer to RtmStatusCode.ChannelMessageState for the message state
                final int errorCode = errorInfo.getErrorCode();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        switch (errorCode) {
                            case RtmStatusCode.ChannelMessageError.CHANNEL_MESSAGE_ERR_TIMEOUT:
                            case RtmStatusCode.ChannelMessageError.CHANNEL_MESSAGE_ERR_FAILURE:
                                ToastUtils.showToast(StartLiveActivity.this, getString(R.string.send_msg_failed));
                                break;
                        }
                    }
                });
            }
        });
    }

    /**
     * API CALL: send message to peer
     */
    private void sendPeerMessage(String content, String userId) {

        // step 1: create a message
        RtmMessage message = mRtmClient.createMessage();
        message.setText(content);
        // step 2: send message to peer
        mRtmClient.sendMessageToPeer(userId, message, new ResultCallback<Void>() {

            @Override
            public void onSuccess(Void aVoid) {
                if (list.size() > positionType) {
                    if (list.get(positionType).getUser().isConnect()) {
                        list.get(positionType).getUser().setConnect(false);
                    } else {
                        list.get(positionType).getUser().setConnect(true);
                    }
                } else {
                    ToastUtils.showToast(StartLiveActivity.this, "数据出错，请退出重试");
                }

            }

            @Override
            public void onFailure(ErrorInfo errorInfo) {
                // refer to RtmStatusCode.PeerMessageState for the message state
                final int errorCode = errorInfo.getErrorCode();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        switch (errorCode) {
                            case RtmStatusCode.PeerMessageError.PEER_MESSAGE_ERR_TIMEOUT:
                            case RtmStatusCode.PeerMessageError.PEER_MESSAGE_ERR_FAILURE:
                                ToastUtils.showToast(StartLiveActivity.this, getString(R.string.send_msg_failed));
                                break;
                            case RtmStatusCode.PeerMessageError.PEER_MESSAGE_ERR_PEER_UNREACHABLE:
                                ToastUtils.showToast(StartLiveActivity.this, getString(R.string.peer_offline));
                                break;
                        }
                    }
                });
            }
        });
    }


    /**
     * API CALL: get channel member list
     */
    private void getChannelMemberList() {
        mRtmChannel.getMembers(new ResultCallback<List<RtmChannelMember>>() {
            @Override
            public void onSuccess(final List<RtmChannelMember> responseInfo) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mChannelMemberCount = responseInfo.size();
                        list.clear();
                        for (int i = 0; i < responseInfo.size(); i++) {
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("userId", responseInfo.get(i).getUserId());
                            jsonObject.put("content", "");
                            jsonObject.put("type", "");
                            jsonObject.put("nickName", "");
                            jsonObject.put("avatar", "");
                            MessageBean messageBean = new MessageBean(String.valueOf(user.getId()), jsonObject.toString(), true);
                            messageBean.setConnect(false);
                            MessageBean.UserInfo userInfo = new MessageBean.UserInfo();
                            userInfo.setAvatar("");
                            userInfo.setContent("");
                            userInfo.setNickName("");
                            userInfo.setConnect(false);
                            userInfo.setUserId(responseInfo.get(i).getUserId());
                            messageBean.setUser(userInfo);
                            list.add(messageBean);
                        }
                        headUserAdapter.setData(list);
                        if (mIsPeerToPeerMode) {
                            sendMessage("欢迎" + user.getNickname() + "来到直播间","1");
                        } else {
                            sendMessage("直播已开启","1");
                        }
                        refreshChannelTitle();
                    }
                });
            }

            @Override
            public void onFailure(ErrorInfo errorInfo) {
                Log.e("登录数据获取消息", "failed to get channel members, err: " + errorInfo.getErrorCode());
            }
        });
    }

    /**
     * API CALLBACK: rtm channel event listener
     */
    class MyChannelListener implements RtmChannelListener {

        @Override
        public void onMessageReceived(final RtmMessage message, final RtmChannelMember fromMember) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    String account = fromMember.getUserId();
                    String msg = message.getText();
                    MessageBean messageBean = new MessageBean(account, msg, false);

//                    messageBean.setBackground(getMessageColor(account));
                    mMessageBeanList.add(messageBean);
                    mMessageAdapter.notifyItemRangeChanged(mMessageBeanList.size(), 1);
                    mRecyclerView.scrollToPosition(mMessageBeanList.size() - 1);
                    try {
                        MessageLiveComment jsonObject= JSON.parseObject(messageBean.getMessage(), MessageLiveComment.class);
                        if(jsonObject.getContent().equals("直播已关闭")){
                            ToastUtils.showToast(StartLiveActivity.this,"直播已关闭");
                            finish();
                        }

                    }catch (Exception e){
                        e.printStackTrace();
                    }
//                    startLiveMessageAdapter.setData(mMessageBeanList);
                }
            });
        }

        @Override
        public void onMemberJoined(RtmChannelMember member) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mChannelMemberCount++;
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("userId", member.getUserId());
                    jsonObject.put("content", "");
                    jsonObject.put("type", "");
                    jsonObject.put("nickName", "");
                    jsonObject.put("avatar", "");
                    MessageBean messageBean = new MessageBean(String.valueOf(user.getId()), jsonObject.toString(), true);
                    messageBean.setConnect(false);
                    MessageBean.UserInfo userInfo = new MessageBean.UserInfo();
                    userInfo.setAvatar("");
                    userInfo.setContent("");
                    userInfo.setNickName("");
                    userInfo.setConnect(false);
                    userInfo.setUserId(member.getUserId());
                    messageBean.setUser(userInfo);
                    list.add(messageBean);
                    headUserAdapter.setData(list);
                    refreshChannelTitle();
                }
            });
        }

        @Override
        public void onMemberLeft(RtmChannelMember member) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mChannelMemberCount--;
                    for (int i = 0; i < list.size(); i++) {
                        MessageLiveComment messageLiveComment = JSON.parseObject(list.get(i).getMessage(), MessageLiveComment.class);
                        if (messageLiveComment != null && messageLiveComment.getUserId() != null && messageLiveComment.getUserId().equals(member.getUserId())) {
                            list.remove(i);
                            break;
                        }
                    }
                    headUserAdapter.setData(list);
                    refreshChannelTitle();
                }
            });
        }
    }

    private void refreshChannelTitle() {
        if (personCount == null) {
            return;
        }
        personCount.setText(mChannelMemberCount + "人观看");
        getLiveUser();

//        String titleFormat = getString(R.string.channel_title);
//        String title = String.format(titleFormat, mChannelName, mChannelMemberCount);
//        mTitleTextView.setText(title);
    }

    private void sendMessage(String content,String type) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("userId", user.getId());
        jsonObject.put("content", content);
        jsonObject.put("type", "3");
        jsonObject.put("isleaver", type);
        jsonObject.put("nickName", user.getNickname());
        jsonObject.put("avatar", user.getImgurl());
        MessageBean messageBean = new MessageBean(String.valueOf(user.getId()), jsonObject.toString(), true);
        mMessageBeanList.add(messageBean);
        mMessageAdapter.notifyItemRangeChanged(mMessageBeanList.size(), 1);
        mRecyclerView.scrollToPosition(mMessageBeanList.size() - 1);
        sendChannelMessage(jsonObject.toString());

    }

    /**
     * API CALL: create and join channel
     */
    private void createAndJoinChannel() {
        // step 1: create a channel instance
        mRtmChannel = mRtmClient.createChannel(roomName, new MyChannelListener());
        if (mRtmChannel == null) {
            finish();
            return;
        }

        // step 2: join the channel
        mRtmChannel.join(new ResultCallback<Void>() {
            @Override
            public void onSuccess(Void responseInfo) {
                getChannelMemberList();
            }

            @Override
            public void onFailure(ErrorInfo errorInfo) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        finish();
                    }
                });
            }
        });
    }

    /**
     * API CALLBACK: rtm event listener
     */
    class MyRtmClientListener implements RtmClientListener {

        @Override
        public void onConnectionStateChanged(final int state, int reason) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    switch (state) {
                        case RtmStatusCode.ConnectionState.CONNECTION_STATE_RECONNECTING:
                            ToastUtils.showToast(StartLiveActivity.this, getString(R.string.reconnecting));
                            break;
                        case RtmStatusCode.ConnectionState.CONNECTION_STATE_ABORTED:
                            ToastUtils.showToast(StartLiveActivity.this, getString(R.string.account_offline));
//                            setResult(MessageUtil.ACTIVITY_RESULT_CONN_ABORTED);
                            finish();
                            break;
                    }
                }
            });
        }

        @Override
        public void onMessageReceived(final RtmMessage message, final String peerId) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    String content = message.getText();
                    if (content.equals("1")) {
                        doConfigEngine(Constants.CLIENT_ROLE_BROADCASTER);
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                beauty.setVisibility(View.VISIBLE);
                                switch_cmera.setVisibility(View.VISIBLE);
                                doRenderRemoteUi(config().mUid);
                            }
                        }, 1000); // wait for reconfig engine
                    } else if (content.equals("2")) {
                        beauty.setVisibility(View.GONE);
                        switch_cmera.setVisibility(View.GONE);
                        doConfigEngine(Constants.CLIENT_ROLE_AUDIENCE);
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                doRemoveRemoteUi(config().mUid);
                            }
                        }, 1000); // wait for reconfig engine

                    }
                }
            });
        }
    }

    /**
     * API CALL: login RTM server
     */
    private void doLogin() {
        mRtmClient.login(null, String.valueOf(user.getId()), new ResultCallback<Void>() {
            @Override
            public void onSuccess(Void responseInfo) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mClientListener = new MyRtmClientListener();
                        mChatManager.registerListener(mClientListener);
                        createAndJoinChannel();

                    }
                });

            }

            @Override
            public void onFailure(ErrorInfo errorInfo) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtils.showToast(StartLiveActivity.this, "登录失败，请退出重试");
                        finish();
                    }
                });

                Log.w("登录数据", "login failed: " + errorInfo.getErrorCode());
            }
        });
    }

    private boolean mIsPeerToPeerMode = true;
    String roomName;

    protected void initUIandEvent() {
        if (isLode == false) {
            return;
        }
        event().addEventHandler(this);
        user = UserManager.getInstance().getUser();

        Intent i = getIntent();
        int cRole = i.getIntExtra(ConstantApp.ACTION_KEY_CROLE, 0);

        if (cRole == 0) {
            throw new RuntimeException("Should not reach here");
        }
        roomName = i.getStringExtra(ConstantApp.ACTION_KEY_ROOM_NAME);
        mIsPeerToPeerMode = i.getBooleanExtra(MessageUtil.INTENT_EXTRA_IS_TYPE, true);

        if (mIsPeerToPeerMode) {
            MessageListBean messageListBean = MessageUtil.getExistMessageListBean(roomName);
            if (messageListBean != null) {
                mMessageBeanList.addAll(messageListBean.getMessageBeanList());
            }
        } else {
            mChannelMemberCount = 1;
        }

        mChatManager = App.getInstance().getChatManager();
        mRtmClient = mChatManager.getRtmClient();
        doLogin();
        doConfigEngine(cRole);
        mGridVideoViewContainer = (GridVideoViewContainer) findViewById(R.id.grid_video_view_container);
        mGridVideoViewContainer.setItemEventHandler(new VideoViewEventListener() {
            @Override
            public void onItemDoubleClick(View v, Object item) {
                if (mUidsList.size() < 2) {
                    return;
                }
                if (mViewType == VIEW_TYPE_DEFAULT)
                    switchToSmallVideoView(((VideoStatusData) item).mUid);
                else
                    switchToDefaultVideoView();
            }

            @Override
            public void onItemClick() {
                beauty_lay.setVisibility(View.VISIBLE);
                chat_lay.setVisibility(View.GONE);
                gift_lay.setVisibility(View.GONE);

            }
        });


//        ImageView button1 = (ImageView) findViewById(R.id.btn_1);
//        ImageView button2 = (ImageView) findViewById(R.id.btn_2);
//        ImageView button3 = (ImageView) findViewById(R.id.btn_3);

        if (isBroadcaster(cRole)) {
            SurfaceView surfaceV = RtcEngine.CreateRendererView(getApplicationContext());
            rtcEngine().setupLocalVideo(new VideoCanvas(surfaceV, VideoCanvas.RENDER_MODE_HIDDEN, 0));

            mUidsList.put(0, surfaceV); // get first surface view

            mGridVideoViewContainer.initViewContainer(getApplicationContext(), 0, mUidsList); // first is now full view
            worker().preview(true, surfaceV, 0);
//            broadcasterUI(button1, button2, button3);
        } else {
//            audienceUI(button1, button2, button3);
        }
        worker().joinChannel(roomName, config().mUid);

    }

    private void doConfigEngine(int cRole) {
        SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
        int prefIndex = pref.getInt(ConstantApp.PrefManager.PREF_PROPERTY_PROFILE_IDX, ConstantApp.DEFAULT_PROFILE_IDX);
        if (prefIndex > ConstantApp.VIDEO_DIMENSIONS.length - 1) {
            prefIndex = ConstantApp.DEFAULT_PROFILE_IDX;
        }
        VideoEncoderConfiguration.VideoDimensions dimension = ConstantApp.VIDEO_DIMENSIONS[prefIndex];

        worker().configEngine(cRole, dimension);
    }

    private User mUser;
    private RoundedImageView avatar_comment;

    @Override
    protected void findId() {
        horizon_head_lv = findViewById(R.id.horizon_head_lv);
        avatar_comment = findViewById(R.id.avatar_comment);
        back_comment = findViewById(R.id.back_comment);
        attent = findViewById(R.id.attent);
        beauty_lay = findViewById(R.id.beauty_lay);
        chat_lay = findViewById(R.id.chat_lay);
        up_image = findViewById(R.id.up_image);
        chat = findViewById(R.id.chat);
        gift = findViewById(R.id.gift);
        gift_lay = findViewById(R.id.gift_lay);
        comment_lay = findViewById(R.id.comment_lay);
//        content_bottom = findViewById(R.id.content_bottom);

        comment_content = findViewById(R.id.comment_content);
        back_image = findViewById(R.id.back_image);
        beauty = findViewById(R.id.beauty);
        switch_cmera = findViewById(R.id.switch_camera);
        user_lay = findViewById(R.id.user_lay);
        invite = findViewById(R.id.invite);
        gift_1 = findViewById(R.id.gift_1);
        gift_2 = findViewById(R.id.gift_2);
        attent_1 = findViewById(R.id.attent_1);
        attent_2 = findViewById(R.id.attent_2);
        nickName = findViewById(R.id.nickName);
        personCount = findViewById(R.id.personCount);
        content_lay = findViewById(R.id.content_lay);
        send = findViewById(R.id.send);
        avatar = findViewById(R.id.avatar);
        mRecyclerView = (RecyclerView) findViewById(R.id.message_list);
        mUser = (User) getIntent().getSerializableExtra("user");
        initVisiable();
    }

    private ChooseLiveUserDialog mDialog;
    private int positionType;

    private void dialogConfig(String content, int position) {
        if (list.size()>0&&list.get(position).getUser().isConnect()) {
            mDialog = new ChooseLiveUserDialog(StartLiveActivity.this, content, true);
        } else {
            mDialog = new ChooseLiveUserDialog(StartLiveActivity.this, content, false);
        }
        mDialog.show();
        mDialog.setOnClickLinstener(new ChooseLiveUserDialog.OnClickLinstener() {
            @Override
            public void onConfig() {
                //        Constants.CLIENT_ROLE_AUDIENCE  观众
                if (ConstantApp.isFastDoubleClick(1500)) {
                    return;
                }
                if (content != null && !content.equals("") && (content.equals("请确认是否关闭直播") || content.equals("请确认是否退出直播间"))) {
                    exitLive();
                } else {
                    positionType = position;
                    if(bottomView_user!=null){
                        bottomView_user.dismissBottomView();
                    }
                    if (list.get(position).getUser().isConnect()) {
                        MessageLiveComment messageLiveComment = JSON.parseObject(list.get(position).getMessage(), MessageLiveComment.class);
                        sendPeerMessage("2", messageLiveComment.getUserId());

                    } else {
                        MessageLiveComment messageLiveComment = JSON.parseObject(list.get(position).getMessage(), MessageLiveComment.class);
                        sendPeerMessage("1", messageLiveComment.getUserId());

                    }

                }
                mDialog.dismiss();
            }

            @Override
            public void onExit() {
                mDialog.dismiss();
            }
        });

    }

    private FaceBeautificationPopupWindow mFaceBeautificationPopupWindow;

    public void getBeauty() {
        if (mFaceBeautificationPopupWindow == null) {
            mFaceBeautificationPopupWindow = new FaceBeautificationPopupWindow(this.getBaseContext());
        }

        if (!mFaceBeautificationPopupWindow.isShowing()) {
            mFaceBeautificationPopupWindow.show(beauty, new FaceBeautificationPopupWindow.UserEventHandler() {
                @Override
                public void onFBSwitch(boolean on) {
                    if (on) {
                        ConstantApp.BEAUTY_EFFECT_ENABLED = true;
                        worker().enablePreProcessor();
                    } else {
                        worker().disablePreProcessor();
                        ConstantApp.BEAUTY_EFFECT_ENABLED = false;
                    }
                }

                @Override
                public void onLightnessSet(float lightness) {
                    worker().setBeautyEffectParameters(lightness, ConstantApp.BEAUTY_OPTIONS.smoothnessLevel, ConstantApp.BEAUTY_OPTIONS.rednessLevel);
                }

                @Override
                public void onSmoothnessSet(float smoothness) {
                    worker().setBeautyEffectParameters(ConstantApp.BEAUTY_OPTIONS.lighteningLevel, smoothness, ConstantApp.BEAUTY_OPTIONS.rednessLevel);
                }

                @Override
                public void onRednessSet(float redness) {
                    worker().setBeautyEffectParameters(ConstantApp.BEAUTY_OPTIONS.lighteningLevel, ConstantApp.BEAUTY_OPTIONS.smoothnessLevel, redness);
                }
            });
        }
    }
    private IWXAPI api;
    private String mInviteCode;

    @Override
    protected void setupView() {
        api = WXAPIFactory.createWXAPI(this, Constant.WX_APPID);
        api.registerApp(Constant.WX_APPID);

        mInviteCode = UserManager.getInstance().getUser().getRequestCode();

        headUserAdapter = new HeadUserAdapter(StartLiveActivity.this, list, false);
        horizon_head_lv.setAdapter(headUserAdapter);
        horizon_head_lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (mIsPeerToPeerMode) {
                    return;
                }
                MessageBean.UserInfo messageLiveComment = list.get(i).getUser();
                if(mUser!=null&&list.get(i).getUser().getUserId().equals(String.valueOf(mUser.getId()))){
                    ToastUtils.showToast(StartLiveActivity.this,"不能对自己进行连麦");
                    return;
                }
                perConSum=0;
                for (int j=0;j<list.size();j++){
                    if(list.get(j).getUser().isConnect()){
                        perConSum++;
                    }
                }
                if (messageLiveComment.isConnect() == false) {
                    if(perConSum<2){
                        if (messageLiveComment.getNickName() != null || !messageLiveComment.getNickName().equals("")) {
                            dialogConfig(messageLiveComment.getNickName(), i);
                        } else {
                            dialogConfig("", i);
                        }

                    }else {
                        ToastUtils.showToast(StartLiveActivity.this,"当前只支持3个人同时视频");
                    }

                } else {
                    if (messageLiveComment.getNickName() != null || !messageLiveComment.getNickName().equals("")) {
                        dialogConfig(messageLiveComment.getNickName(), i);
                    } else {
                        dialogConfig("", i);
                    }

                }



            }
        });

    }

    private int resId[] = new int[]{R.mipmap.icon_flowers, R.mipmap.icon_car, R.mipmap.icon_love, R.mipmap.icon_rocket, R.mipmap.icon_starlight, R.mipmap.icon_perfume, R.mipmap.icon_love_you, R.mipmap.icon_applaud};
    private String name[] = new String[]{"鲜花", "跑车", "爱心", "火箭", "星光", "香水", "爱你", "鼓掌"};
    private String money[] = new String[]{"399早币", "1288早币", "99早币", "18888早币", "399早币", "588早币", "99早币", "18888早币"};
    private StartLiveAdapter startLiveAdapter;
    private BottomView bottomView;
    private List<GiftBean> list_bot = new ArrayList<>();
    private int giftPosition;
    private int perConSum=0;

    private int num_sum=1;

    private void showPopWindow() {

        bottomView = new BottomView(StartLiveActivity.this, R.style.BottomViewTheme_Defalut, R.layout.activity_start_live_bottom);
        bottomView.setAnimation(R.style.myStyle);
        bottomView.dismissBottomView();
        bottomView.showBottomView(true);
        GridView grid_view = bottomView.getView().findViewById(R.id.grid_view);
        TextView send = bottomView.getView().findViewById(R.id.send);
        TextView score = bottomView.getView().findViewById(R.id.score);
        EditText number = bottomView.getView().findViewById(R.id.number);
        TextView jia = bottomView.getView().findViewById(R.id.jia);
        TextView jian = bottomView.getView().findViewById(R.id.jian);
        TextView gift_top = bottomView.getView().findViewById(R.id.gift_top);

        TextView center_top = bottomView.getView().findViewById(R.id.center_top);
        LinearLayout center_botttom = bottomView.getView().findViewById(R.id.center_botttom);

         if(mIsPeerToPeerMode){
             getGiftList();
             center_top.setVisibility(View.GONE);
             center_botttom.setVisibility(View.VISIBLE);
             gift_top.setVisibility(View.VISIBLE);
             score.setVisibility(View.VISIBLE);
        }else {
             getGiftListLift();
             center_top.setVisibility(View.VISIBLE);
             center_botttom.setVisibility(View.GONE);
             gift_top.setVisibility(View.GONE);
             score.setVisibility(View.GONE);
         }

        score.setText("剩余早币："+UserManager.getInstance().getUser().getScore());
        startLiveAdapter = new StartLiveAdapter(StartLiveActivity.this, list_bot, false,mIsPeerToPeerMode);
        grid_view.setAdapter(startLiveAdapter);
        startLiveAdapter.setData(list_bot);
        jia.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(TextUtils.isEmpty(number.getText())){
                    number.setText("2");
                }else {
                    number.setText(String.valueOf(Integer.parseInt(number.getText().toString())+1));
                }

            }
        });
        jian.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(TextUtils.isEmpty(number.getText())||Integer.parseInt(number.getText().toString())<=1){
                    number.setText("1");
                }else {
                    number.setText(String.valueOf(Integer.parseInt(number.getText().toString())-1));
                }

            }
        });
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(list_bot.size()>0){
                        if(TextUtils.isEmpty(number.getText())){
                            setGift(String.valueOf(list_bot.get(giftPosition).getId()),list_bot.get(giftPosition).getName(),"1");
                        }else {
                            setGift(String.valueOf(list_bot.get(giftPosition).getId()),list_bot.get(giftPosition).getName(),number.getText().toString());

                        }
                        bottomView.dismissBottomView();

                }
            }
        });
        grid_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {

                for (int i = 0; i < list_bot.size(); i++) {
                    list_bot.get(i).setSelect(false);
                }
                giftPosition=position;
                list_bot.get(position).setSelect(true);
                startLiveAdapter.setData(list_bot);
            }
        });

    }

    private BottomView bottomView_user;
    private UserInfoAdapter userInfoAdapter;

    private void showPopWindowUser() {
        if(list.size()<=0){
            ToastUtils.showToast(StartLiveActivity.this,"暂时没有可连接观众");
            return;
        }
        bottomView_user = new BottomView(StartLiveActivity.this, R.style.BottomViewTheme_Defalut, R.layout.item_user_pop);
        bottomView_user.setAnimation(R.style.myStyle);
        bottomView_user.dismissBottomView();
        bottomView_user.showBottomView(true);
        ListView list_user_lv = bottomView_user.getView().findViewById(R.id.list_user_lv);
        userInfoAdapter = new UserInfoAdapter(StartLiveActivity.this, list, false);
        list_user_lv.setAdapter(userInfoAdapter);
        list_user_lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if(mUser!=null&&list.get(i).getUser().getUserId().equals(String.valueOf(mUser.getId()))){
                    ToastUtils.showToast(StartLiveActivity.this,"不能对自己进行连麦");
                    return;
                }
                perConSum=0;
                for (int j=0;j<list.size();j++){
                    if(list.get(j).getUser().isConnect()){
                        perConSum++;
                    }
                }

                MessageBean.UserInfo messageLiveComment = list.get(i).getUser();
                if (messageLiveComment.isConnect() == false) {
                    if(perConSum<2){
                        if (messageLiveComment.getNickName() != null || !messageLiveComment.getNickName().equals("")) {
                            dialogConfig(messageLiveComment.getNickName(), i);
                        } else {
                            dialogConfig("", i);
                        }

                    }else {
                        ToastUtils.showToast(StartLiveActivity.this,"当前只支持3个人同时视频");
                    }

                } else {

                    if (messageLiveComment.getNickName() != null || !messageLiveComment.getNickName().equals("")) {
                        dialogConfig(messageLiveComment.getNickName(), i);
                    } else {
                        dialogConfig("", i);
                    }

                }


            }
        });

    }

    ImageView gift_1, attent_1, attent_2, switch_cmera, invite;
    LinearLayout user_lay;
    private RoundedImageView avatar;
    private TextView nickName, personCount;

    ImageView gift_2;

    public void getUserFollow() {
        long id = UserManager.getInstance().getUser().getId();
        addSubscription(mApiService.getIsFollow(id,mUser.getId())
                , new SubscriberCallBack<Boolean>(StartLiveActivity.this) {
                    @Override
                    protected void onSuccess(Boolean b) {
                        if (mUser.getId() != UserManager.getInstance().getUser().getId()) {
                            attent.setText(mUser.isHasFollow() ? "已关注" : "关注");
                        }

                    }

                    @Override
                    protected void onFailure(ResultResponse response) {
                    }

                });
    }

    private void initVisiable() {
        mIsPeerToPeerMode = getIntent().getBooleanExtra(MessageUtil.INTENT_EXTRA_IS_TYPE, true);
        if (mUser.getId() != UserManager.getInstance().getUser().getId()) {
            attent.setText(mUser.isHasFollow() ? "已关注" : "关注");
        }
        getUserFollow();
        personCount.setText(mChannelMemberCount + "人观看");
        if (mUser.getImgurl() == null || mUser.getImgurl().equals("")) {
            avatar.setImageResource(R.mipmap.default_head_women);
        } else {
            Glide.with(this).load(Constant.IMAGE_PREFIX + mUser.getImgurl()).into(avatar);
        }
        if (UserManager.getInstance().getUser().getImgurl() == null || UserManager.getInstance().getUser().getImgurl().equals("")) {
            avatar_comment.setImageResource(R.mipmap.default_head_women);
        } else {
            Glide.with(this).load(Constant.IMAGE_PREFIX + UserManager.getInstance().getUser().getImgurl()).into(avatar_comment);
        }

        nickName.setText(TextUtils.isEmpty(mUser.getNickname()) ? "" : mUser.getNickname());

        if (mIsPeerToPeerMode) {
            beauty.setVisibility(View.GONE);
            switch_cmera.setVisibility(View.GONE);
            gift.setVisibility(View.VISIBLE);
            invite.setVisibility(View.GONE);
            user_lay.setVisibility(View.VISIBLE);
            attent_1.setVisibility(View.VISIBLE);
            attent_2.setVisibility(View.VISIBLE);
            comment_content.setHint("来都来了，说点什么吧...");
        } else {
            beauty.setVisibility(View.VISIBLE);
            switch_cmera.setVisibility(View.VISIBLE);
            gift.setVisibility(View.GONE);
            invite.setVisibility(View.VISIBLE);
            user_lay.setVisibility(View.GONE);
            attent_1.setVisibility(View.GONE);
            attent_2.setVisibility(View.GONE);
            comment_content.setHint("请输入内容");
        }

    }


    @Override
    protected void setView() {
        setContentView(R.layout.activity_start_live);
    }

    @Override
    protected void initLinstener() {
        back_comment.setOnClickListener(this);
        up_image.setOnClickListener(this);
        gift.setOnClickListener(this);
        back_image.setOnClickListener(this);
        comment_content.setOnClickListener(this);
        gift_1.setOnClickListener(this);
        gift_2.setOnClickListener(this);
        attent_1.setOnClickListener(this);
        attent_2.setOnClickListener(this);
        beauty.setOnClickListener(this);
        switch_cmera.setOnClickListener(this);
        invite.setOnClickListener(this);
        chat.setOnClickListener(this);
        attent.setOnClickListener(this);
        content_lay.setOnClickListener(this);
        send.setOnClickListener(this);
//        content_bottom.setOnClickListener(this);

    }

    private MessageAdapter mMessageAdapter;
    //    private StartLiveMessageAdapter startLiveMessageAdapter;
    private List<MessageBean> mMessageBeanList = new ArrayList<>();

    @Override
    protected void requsetData() {
//        for (int i = 0; i < resId.length; i++) {
//            GiftBean giftBean = new GiftBean();
//            giftBean.setMoney(money[i]);
//            giftBean.setName(name[i]);
//            giftBean.setResid(resId[i]);
//            list_bot.add(giftBean);
//        }
        if(mIsPeerToPeerMode){
            getGiftList();
        }else {
            getGiftListLift();
        }
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(layoutManager);
        layoutManager.setOrientation(OrientationHelper.VERTICAL);
        mMessageAdapter = new MessageAdapter(this, mMessageBeanList);
        mRecyclerView.setAdapter(mMessageAdapter);
        mMessageAdapter.setOnItemClickLinstener(new MessageAdapter.OnItemClickLinstener() {
            @Override
            public void onItemClick() {
                beauty_lay.setVisibility(View.VISIBLE);
                chat_lay.setVisibility(View.GONE);
                gift_lay.setVisibility(View.GONE);

            }
        });

//        startLiveMessageAdapter =new StartLiveMessageAdapter(this,mMessageBeanList,false);
//        comment_lv.setAdapter(startLiveMessageAdapter);
//        headUserAdapter.setData(list);

    }

    private List<MessageBean> list = new ArrayList<>();


    @Override
    public Activity getContext() {
        return null;
    }

    @Override
    public void onRequestSuccess(List<FriendBean> friendBeans) {

    }

    @Override
    public void onRequestNoData(String message) {

    }

    @Override
    public void onRequestError(String error_message) {

    }

    @Override
    public void onStartLiveSuccess() {

    }

    @Override
    public void onFaileds() {

    }

    private KeyMapDailog dialog;

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.up_image:
                chat_lay.setVisibility(View.VISIBLE);
                beauty_lay.setVisibility(View.GONE);
                gift_lay.setVisibility(View.GONE);
                break;
            case R.id.chat:
                chat_lay.setVisibility(View.VISIBLE);
                beauty_lay.setVisibility(View.GONE);
                gift_lay.setVisibility(View.GONE);
                break;
            case R.id.content_lay:
                beauty_lay.setVisibility(View.VISIBLE);
                chat_lay.setVisibility(View.GONE);
                gift_lay.setVisibility(View.GONE);
                break;
//            case R.id.content_bottom:
//                beauty_lay.setVisibility(View.VISIBLE);
//                chat_lay.setVisibility(View.GONE);
//                gift_lay.setVisibility(View.GONE);
//                break;

            case R.id.send:
                ToastUtils.showToast(StartLiveActivity.this,"请输入内容");
                break;
            case R.id.switch_camera:
                worker().getRtcEngine().switchCamera();
                break;
            case R.id.back_comment:
                showSharePopWindow();
            break;
            case R.id.invite:
                showPopWindowUser();
                break;
            case R.id.attent:
                followUser(mUser.getId());
                break;
            case R.id.attent_1:
                followUser(mUser.getId());
                break;
            case R.id.attent_2:
                followUser(mUser.getId());
                break;

            case R.id.back_image:
                if (mIsPeerToPeerMode) {
                    dialogConfig("请确认是否退出直播间", 0);
                } else {
                    dialogConfig("请确认是否关闭直播", 0);
                }
                break;
            case R.id.gift:
                if (gift_lay.getVisibility() == View.VISIBLE) {
                    gift_lay.setVisibility(View.GONE);
                } else {
                    gift_lay.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.gift_1:
                showPopWindow();
                break;
            case R.id.gift_2:
                showPopWindow();
                break;
            case R.id.beauty:
                getBeauty();
                break;


            case R.id.comment_content:
                dialog = new KeyMapDailog("请输入内容", comment_lay, new KeyMapDailog.SendBackListener() {
                    @Override
                    public void sendBack(final String inputText) {
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("userId", user.getId());
                        jsonObject.put("content", inputText);
                        if (mIsPeerToPeerMode) {
                            jsonObject.put("type", user.getType());
                            jsonObject.put("nickName", user.getNickname());
                        } else {
                            jsonObject.put("type", "2");
                            jsonObject.put("nickName", "主播");
                        }
                        jsonObject.put("avatar", user.getImgurl());
                        MessageBean messageBean = new MessageBean(String.valueOf(user.getId()), jsonObject.toString(), true);
                        mMessageBeanList.add(messageBean);
                        mMessageAdapter.notifyItemRangeChanged(mMessageBeanList.size(), 1);
                        mRecyclerView.scrollToPosition(mMessageBeanList.size() - 1);
//                        if (mIsPeerToPeerMode) {
//                            sendPeerMessage(jsonObject.toString());
//                        } else {
                        sendChannelMessage(jsonObject.toString());
//                        }
                        beauty_lay.setVisibility(View.VISIBLE);
                        chat_lay.setVisibility(View.GONE);
                        gift_lay.setVisibility(View.GONE);
                        dialog.dismiss();
                    }
                });
                dialog.show(getSupportFragmentManager(), "dialog");

                break;
        }
    }
    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }
    private void getInterest(){
        HashMap<String,Object> hashMap=new HashMap<>();
        hashMap.put("uid",String.valueOf(UserManager.getInstance().getUser().getId()));
        hashMap.put("content","不感兴趣");
         hashMap.put("type","zb");
        hashMap.put("externalId",getIntent().getIntExtra("idlive",0));
        addSubscription(mApiService.getInterest(hashMap), new SubscriberCallBack<ReportBean>(this) {
            @Override
            protected void onSuccess(ReportBean list) {
                ToastUtils.showToast(StartLiveActivity.this,"已为您添加至不感兴趣");

            }

            @Override
            protected void onFailure(ResultResponse response) {

            }

            @Override
            protected boolean isShowProgress() {
                return false;
            }

            @Override
            protected void onPageSuccess(int currentPage, int allPage, int allSize) {
            }
        });

    }


    private void showSharePopWindow(){
        bottomView=new BottomView(StartLiveActivity.this, R.style.BottomViewTheme_Defalut, R.layout.share_item);
        bottomView.setAnimation(R.style.myStyle);
        bottomView.dismissBottomView();
        bottomView.showBottomView(false);
        TextView exit=bottomView.getView().findViewById(R.id.exit);
        LinearLayout lay_1=bottomView.getView().findViewById(R.id.lay_1);
        LinearLayout lay_2=bottomView.getView().findViewById(R.id.lay_2);
        LinearLayout lay_3=bottomView.getView().findViewById(R.id.lay_3);
        LinearLayout lay_4=bottomView.getView().findViewById(R.id.lay_4);
        LinearLayout lay_5=bottomView.getView().findViewById(R.id.lay_5);
        LinearLayout lay_6=bottomView.getView().findViewById(R.id.lay_6);
        lay_6.setVisibility(View.GONE);
        lay_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Util.shareWeb(StartLiveActivity.this,api,SendMessageToWX.Req.WXSceneSession);

                bottomView.dismissBottomView();
            }
        });
        lay_2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ToastUtils.showToast(StartLiveActivity.this,"此功能暂未开放");
                bottomView.dismissBottomView();
            }
        });
        lay_3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ToastUtils.showToast(StartLiveActivity.this,"此功能暂未开放");
                bottomView.dismissBottomView();
            }
        });
        lay_4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Util.shareWeb(StartLiveActivity.this,api,SendMessageToWX.Req.WXSceneTimeline);
                bottomView.dismissBottomView();
            }
        });
        lay_5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getInterest();
                bottomView.dismissBottomView();
            }
        });
        exit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                bottomView.dismissBottomView();
            }
        });

    }


    protected RtcEngine rtcEngine() {
        return ((App) getApplication()).getWorkerThread().getRtcEngine();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mIsPeerToPeerMode) {
                dialogConfig("请确认是否退出直播间", 0);
            } else {
                dialogConfig("请确认是否关闭直播", 0);
            }
        }
        return true;

    }


    @Override
    public void onFirstRemoteVideoDecoded(int uid, int width, int height, int elapsed) {

    }

    @Override
    public void onJoinChannelSuccess(final String channel, final int uid, final int elapsed) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (isFinishing()) {
                    return;
                }

                if (mUidsList.containsKey(uid)) {
//                    log.debug("already added to UI, ignore it " + (uid & 0xFFFFFFFFL) + " " + mUidsList.get(uid));
                    return;
                }

                final boolean isBroadcaster = isBroadcaster();
//                log.debug("onJoinChannelSuccess " + channel + " " + uid + " " + elapsed + " " + isBroadcaster);

                worker().getEngineConfig().mUid = uid;

                SurfaceView surfaceV = mUidsList.remove(0);
                if (surfaceV != null) {
                    mUidsList.put(uid, surfaceV);
                }
            }
        });

    }

    @Override
    public void onUserOffline(int uid, int reason) {
        doRemoveRemoteUi(uid);
    }

    @Override
    public void onUserJoined(int uid, int elapsed) {
        doRenderRemoteUi(uid);
    }

    private void doRemoveRemoteUi(final int uid) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (isFinishing()) {
                    return;
                }

                mUidsList.remove(uid);

                int bigBgUid = -1;
                if (mSmallVideoViewAdapter != null) {
                    bigBgUid = mSmallVideoViewAdapter.getExceptedUid();
                }

//                log.debug("doRemoveRemoteUi " + (uid & 0xFFFFFFFFL) + " " + (bigBgUid & 0xFFFFFFFFL));

                if (mViewType == VIEW_TYPE_DEFAULT || uid == bigBgUid) {
                    switchToDefaultVideoView();
                } else {
                    switchToSmallVideoView(bigBgUid);
                }
            }
        });
    }

    private void doRenderRemoteUi(final int uid) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (isFinishing()) {
                    return;
                }

                SurfaceView surfaceV = RtcEngine.CreateRendererView(getApplicationContext());
                mUidsList.put(uid, surfaceV);
                if (config().mUid == uid) {
                    rtcEngine().setupLocalVideo(new VideoCanvas(surfaceV, VideoCanvas.RENDER_MODE_HIDDEN, uid));
                } else {
                    rtcEngine().setupRemoteVideo(new VideoCanvas(surfaceV, VideoCanvas.RENDER_MODE_HIDDEN, uid));
                }

                if (mViewType == VIEW_TYPE_DEFAULT) {
//                    log.debug("doRenderRemoteUi VIEW_TYPE_DEFAULT" + " " + (uid & 0xFFFFFFFFL));
                    switchToDefaultVideoView();
                } else {
                    int bigBgUid = mSmallVideoViewAdapter.getExceptedUid();
//                    log.debug("doRenderRemoteUi VIEW_TYPE_SMALL" + " " + (uid & 0xFFFFFFFFL) + " " + (bigBgUid & 0xFFFFFFFFL));
                    switchToSmallVideoView(bigBgUid);
                }
            }
        });
    }

    private void bindToSmallVideoView(int exceptUid) {
        if (mSmallVideoViewDock == null) {
            ViewStub stub = (ViewStub) findViewById(R.id.small_video_view_dock);
            stub.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    beauty_lay.setVisibility(View.VISIBLE);
                    chat_lay.setVisibility(View.GONE);
                    gift_lay.setVisibility(View.GONE);
                }
            });
            mSmallVideoViewDock = (RelativeLayout) stub.inflate();
        }
        RecyclerView recycler = (RecyclerView) findViewById(R.id.small_video_view_container);

        boolean create = false;

        if (mSmallVideoViewAdapter == null) {
            create = true;
            mSmallVideoViewAdapter = new SmallVideoViewAdapter(this, exceptUid, mUidsList, new VideoViewEventListener() {
                @Override
                public void onItemDoubleClick(View v, Object item) {
                    switchToDefaultVideoView();
                }

                @Override
                public void onItemClick() {
                    beauty_lay.setVisibility(View.VISIBLE);
                    chat_lay.setVisibility(View.GONE);
                    gift_lay.setVisibility(View.GONE);
                }
            });
            mSmallVideoViewAdapter.setHasStableIds(true);
        }
        recycler.setHasFixedSize(true);

        recycler.setLayoutManager(new GridLayoutManager(this, 3, GridLayoutManager.VERTICAL, false));
        recycler.setAdapter(mSmallVideoViewAdapter);

        recycler.setDrawingCacheEnabled(true);
        recycler.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_AUTO);

        if (!create) {
            mSmallVideoViewAdapter.notifyUiChanged(mUidsList, exceptUid, null, null);
        }
        for (Integer tempUid : mUidsList.keySet()) {
            if (config().mUid != tempUid) {
                if (tempUid == exceptUid) {
                    rtcEngine().setRemoteUserPriority(tempUid, Constants.USER_PRIORITY_HIGH);
//                    log.debug("setRemoteUserPriority USER_PRIORITY_HIGH " + mUidsList.size() + " " + (tempUid & 0xFFFFFFFFL));
                } else {
                    rtcEngine().setRemoteUserPriority(tempUid, Constants.USER_PRIORITY_NORANL);
//                    log.debug("setRemoteUserPriority USER_PRIORITY_NORANL " + mUidsList.size() + " " + (tempUid & 0xFFFFFFFFL));
                }
            }
        }


        recycler.setVisibility(View.VISIBLE);
        mSmallVideoViewDock.setVisibility(View.VISIBLE);
    }

    private void switchToSmallVideoView(int uid) {
        HashMap<Integer, SurfaceView> slice = new HashMap<>(1);
        slice.put(uid, mUidsList.get(uid));
        mGridVideoViewContainer.initViewContainer(getApplicationContext(), uid, slice);

        bindToSmallVideoView(uid);

        mViewType = VIEW_TYPE_SMALL;

        requestRemoteStreamType(mUidsList.size());
    }

    private void requestRemoteStreamType(final int currentHostCount) {
//        log.debug("requestRemoteStreamType " + currentHostCount);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                HashMap.Entry<Integer, SurfaceView> highest = null;
                for (HashMap.Entry<Integer, SurfaceView> pair : mUidsList.entrySet()) {
//                    log.debug("requestRemoteStreamType " + currentHostCount + " local " + (config().mUid & 0xFFFFFFFFL) + " " + (pair.getKey() & 0xFFFFFFFFL) + " " + pair.getValue().getHeight() + " " + pair.getValue().getWidth());
                    if (pair.getKey() != config().mUid && (highest == null || highest.getValue().getHeight() < pair.getValue().getHeight())) {
                        if (highest != null) {
                            rtcEngine().setRemoteVideoStreamType(highest.getKey(), Constants.VIDEO_STREAM_LOW);
//                            log.debug("setRemoteVideoStreamType switch highest VIDEO_STREAM_LOW " + currentHostCount + " " + (highest.getKey() & 0xFFFFFFFFL) + " " + highest.getValue().getWidth() + " " + highest.getValue().getHeight());
                        }
                        highest = pair;
                    } else if (pair.getKey() != config().mUid && (highest != null && highest.getValue().getHeight() >= pair.getValue().getHeight())) {
                        rtcEngine().setRemoteVideoStreamType(pair.getKey(), Constants.VIDEO_STREAM_LOW);
//                        log.debug("setRemoteVideoStreamType VIDEO_STREAM_LOW " + currentHostCount + " " + (pair.getKey() & 0xFFFFFFFFL) + " " + pair.getValue().getWidth() + " " + pair.getValue().getHeight());
                    }
                }
                if (highest != null && highest.getKey() != 0) {
                    rtcEngine().setRemoteVideoStreamType(highest.getKey(), Constants.VIDEO_STREAM_HIGH);
//                    log.debug("setRemoteVideoStreamType VIDEO_STREAM_HIGH " + currentHostCount + " " + (highest.getKey() & 0xFFFFFFFFL) + " " + highest.getValue().getWidth() + " " + highest.getValue().getHeight());
                }
            }
        }, 500);
    }

    private void switchToDefaultVideoView() {
        if (mSmallVideoViewDock != null)
            mSmallVideoViewDock.setVisibility(View.GONE);
        mGridVideoViewContainer.initViewContainer(getApplicationContext(), config().mUid, mUidsList);

        mViewType = VIEW_TYPE_DEFAULT;

        int sizeLimit = mUidsList.size();
        if (sizeLimit > ConstantApp.MAX_PEER_COUNT + 1) {
            sizeLimit = ConstantApp.MAX_PEER_COUNT + 1;
        }
        for (int i = 0; i < sizeLimit; i++) {
            int uid = mGridVideoViewContainer.getItem(i).mUid;
            if (config().mUid != uid) {
                rtcEngine().setRemoteVideoStreamType(uid, Constants.VIDEO_STREAM_HIGH);
//                log.debug("setRemoteVideoStreamType VIDEO_STREAM_HIGH " + mUidsList.size() + " " + (uid & 0xFFFFFFFFL));
            }
        }
        boolean setRemoteUserPriorityFlag = false;
        for (int i = 0; i < sizeLimit; i++) {
            int uid = mGridVideoViewContainer.getItem(i).mUid;
            if (config().mUid != uid) {
                if (!setRemoteUserPriorityFlag) {
                    setRemoteUserPriorityFlag = true;
                    rtcEngine().setRemoteUserPriority(uid, Constants.USER_PRIORITY_HIGH);
//                    log.debug("setRemoteUserPriority USER_PRIORITY_HIGH " + mUidsList.size() + " " + (uid & 0xFFFFFFFFL));
                } else {
                    rtcEngine().setRemoteUserPriority(uid, Constants.USER_PRIORITY_NORANL);
//                    log.debug("setRemoteUserPriority USER_PRIORITY_NORANL " + mUidsList.size() + " " + (uid & 0xFFFFFFFFL));
                }
            }
        }
    }

    public void exitFinishLive() {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("id", getIntent().getIntExtra("idlive",0));
        addSubscription(mApiService.exitFinishLive(getIntent().getIntExtra("idlive",0)), new SubscriberCallBack<String>(this) {
            @Override
            protected void onSuccess(String msg) {
                if (mIsPeerToPeerMode) {
                    sendMessage(user.getNickname() + "退出了直播间","0");
                } else {
                    sendMessage("直播已关闭","0");
                }
                mRtmClient.logout(null);
                finish();
            }

            @Override
            protected boolean isShowProgress() {
                return true;
            }

            @Override
            protected void onFailure(ResultResponse response) {
                ToastUtils.showToast(StartLiveActivity.this, response.getMessage());
                sendMessage("直播已关闭","0");
                mRtmClient.logout(null);
                finish();
            }
        });
    }
    public void exitLive() {
        if (!mIsPeerToPeerMode) {
            exitFinishLive();
            return;
        }
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("id", getIntent().getStringExtra("bid"));
        hashMap.put("uid", UserManager.getInstance().getUser().getId());
        addSubscription(mApiService.exitLive(hashMap), new SubscriberCallBack<String>(this) {
            @Override
            protected void onSuccess(String msg) {
                sendMessage(user.getNickname() + "退出了直播间","0");
                mRtmClient.logout(null);
                finish();
            }

            @Override
            protected boolean isShowProgress() {
                return true;
            }

            @Override
            protected void onFailure(ResultResponse response) {
                ToastUtils.showToast(StartLiveActivity.this, response.getMessage());
                if (mIsPeerToPeerMode) {
                    sendMessage(user.getNickname() + "退出了直播间","0");
                } else {
                    sendMessage("直播已关闭","0");
                }
                mRtmClient.logout(null);
                finish();
            }
        });
    }
    public void getLiveUser() {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("bid", getIntent().getStringExtra("bid"));
        addSubscription(mApiService.getLiveUser(hashMap), new SubscriberCallBack<List<LiveUserBean>>(this) {
            @Override
            protected void onSuccess(List<LiveUserBean> liveUserBeans) {
                for (int j = 0; j < list.size(); j++) {
                    for (int i = 0; i < liveUserBeans.size(); i++) {
                        if(list.get(j).getUser().getUserId().equals(liveUserBeans.get(i).getUid())){
                            list.get(j).getUser().setNickName(liveUserBeans.get(i).getNickname());
                            list.get(j).getUser().setAvatar(liveUserBeans.get(i).getImgurl());
                            break;
                        }

                    }
                }
                for (int j = 0; j < list.size(); j++) {
                    if(list.get(j).getUser().getUserId().equals(String.valueOf(mUser.getId()))){
                        list.remove(j);
                    }
                }
                headUserAdapter.setData(list);
                userInfoAdapter.setData(list);

            }

            @Override
            protected boolean isShowProgress() {
                return true;
            }

            @Override
            protected void onFailure(ResultResponse response) {
                ToastUtils.showToast(StartLiveActivity.this, response.getMessage());
            }
        });
    }
    public void setGift(String giftId,String name,String number) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("uid",UserManager.getInstance().getUser().getId());
        hashMap.put("liveId",getIntent().getIntExtra("idlive",0));
        hashMap.put("giftId",giftId);
        hashMap.put("count",number);
        addSubscription(mApiService.setGift(hashMap), new SubscriberCallBack<String>(this) {
            @Override
            protected void onSuccess(String msg) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("userId", user.getId());
                jsonObject.put("content", user.getNickname()+"送给主播"+name+"x"+number);
                jsonObject.put("type", "3");
                jsonObject.put("nickName", user.getNickname());
                jsonObject.put("avatar", user.getImgurl());
                MessageBean messageBean = new MessageBean(String.valueOf(user.getId()), jsonObject.toString(), true);
                mMessageBeanList.add(messageBean);
                mMessageAdapter.notifyItemRangeChanged(mMessageBeanList.size(), 1);
                mRecyclerView.scrollToPosition(mMessageBeanList.size() - 1);
                sendChannelMessage(jsonObject.toString());

            }

            @Override
            protected boolean isShowProgress() {
                return true;
            }

            @Override
            protected void onFailure(ResultResponse response) {
                ToastUtils.showToast(StartLiveActivity.this, response.getMessage());
            }
        });
    }
    public void getGiftList() {
        HashMap<String, Object> hashMap = new HashMap<>();
        addSubscription(mApiService.getGiftList(), new SubscriberCallBack<List<GiftBean>>(this) {
            @Override
            protected void onSuccess(List<GiftBean> giftBeans) {
                if(giftBeans!=null&&giftBeans.size()>0){
                    list_bot.clear();
                    list_bot.addAll(giftBeans);
                    if(startLiveAdapter!=null){
                        startLiveAdapter.setData(list_bot);
                    }

                }

            }

            @Override
            protected boolean isShowProgress() {
                return true;
            }

            @Override
            protected void onFailure(ResultResponse response) {
                ToastUtils.showToast(StartLiveActivity.this, response.getMessage());
            }
        });
    }
    public void getGiftListLift() {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("uid",UserManager.getInstance().getUser().getId());
        hashMap.put("liveId",getIntent().getIntExtra("idlive",0));
        Log.w("礼物列表",""+hashMap.toString());
        addSubscription(mApiService.getGiftListLift(hashMap), new SubscriberCallBack<List<GiftBean>>(this) {
            @Override
            protected void onSuccess(List<GiftBean> giftBeans) {
                if(giftBeans!=null&&giftBeans.size()>0){
                    list_bot.clear();
                    list_bot.addAll(giftBeans);
                    if(startLiveAdapter!=null){
                        startLiveAdapter.setData(list_bot);
                    }

                }

            }

            @Override
            protected boolean isShowProgress() {
                return true;
            }

            @Override
            protected void onFailure(ResultResponse response) {
                ToastUtils.showToast(StartLiveActivity.this, response.getMessage());
            }
        });
    }

    public void followUser(long followId) {
        long id = UserManager.getInstance().getUser().getId();
        addSubscription(mApiService.followUser(id, followId), new SubscriberCallBack<String>(this) {
            @Override
            protected void onSuccess(String success) {
                List<FollowFan> list = new ArrayList();
                FollowFan fan = new FollowFan();
                fan.setId(0);
                fan.setFollowUid(success == null ? 1 : 0);
                list.add(fan);
                if (list.size() == 1) {
                    if (attent.getText().toString().equals("已关注")) {
                        ToastUtils.showToast(StartLiveActivity.this, "取消关注成功");
                        attent.setText("关注");
                    } else {
                        ToastUtils.showToast(StartLiveActivity.this, "关注成功");
                        attent.setText("已关注");
                    }
                }

            }

            @Override
            protected boolean isShowProgress() {
                return true;
            }

            @Override
            protected void onFailure(ResultResponse response) {
                ToastUtils.showToast(StartLiveActivity.this, response.getMessage());
            }
        });
    }

    public void addSubscription(Observable observable, Subscriber subscriber) {
        if (mCompositeSubscription == null) {
            mCompositeSubscription = new CompositeSubscription();
        }
        mCompositeSubscription.add(observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber));
    }

    @Override
    public void onLastmileQuality(int quality) {

    }

    @Override
    public void onLastmileProbeResult(IRtcEngineEventHandler.LastmileProbeResult result) {

    }
}
